<template>
    <div>
        <Dialog :show="dialogConfig.show" :title="dialogConfig.title" :buttons="dialogConfig.buttons" width="500px"
            :showCancel="false" @close="dialogConfig.show = false">
            <el-form :model="formData" label-width="80px" :rules="rules" ref="formDataRef" @submit.prevent>
                <el-form-item label="新密码" prop="password">
                    <el-input v-model.trim="formData.password" type="password" size="large" maxLength="20" show-password
                        placeholder="新密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="rePassword">
                    <el-input v-model.trim="formData.rePassword" type="password" size="large" maxLength="20"
                        show-password placeholder="确认密码"></el-input>
                </el-form-item>
            </el-form>
        </Dialog>
    </div>
</template>

<script setup>
import { number } from 'echarts';
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';


const api = {
    // 修改密码
    updateMyPassword: '/merchant/welcomePage/updateMyPassword',
    // 管理员修改密码
    updateMerPwd: '/admin/updateMerPwd'
}

const { proxy } = getCurrentInstance();

const dialogConfig = ref({
    show: false,
    title: '修改密码',
    buttons: [
        {
            type: 'primary',
            text: '确定',
            click: (e) => {
                save()
            }
        }
    ]
})


// 确认密码比对
const checkRePassword = (rule, value, callback) => {
    if (value !== formData.value.password) {
        callback(new Error('两次输入密码不一致'));
    } else {
        callback();
    }
};

const formData = ref({})
const formDataRef = ref()
const rules = {
    password: [
        { required: true, message: '新密码不能为空' },
        { validator: proxy.Verfiy.password, message: "密码需 8-18 位，并包含字母和数字" },
    ],
    rePassword: [
        { required: true, message: '确认密码不能为空' },
        { validator: checkRePassword, message: '两次输入密码不一致' }
    ],
}

const email = ref();

const show = (value) => {
    dialogConfig.value.show = true
    email.value = value
    nextTick(() => {
        formDataRef.value.resetFields()
        formData.value = {}
    })
}

const save = () => {
    formDataRef.value.validate(async (valid) => {
        if (!valid) {
            return;
        }
            
        let params = {}
        Object.assign(params, formData.value)
        let url = null
        if (props.status === 0) {
            params.email = email.value
            url = api.updateMerPwd
        } else {
            url = api.updateMyPassword
        }

        let result = await proxy.Request({
            url,
            params,
        })
        if (!result) {
            return
        }
        proxy.Message.success("修改密码成功")
        dialogConfig.value.show = false
    })
}

const props = defineProps({
    email: String,
    status: Number,
})

defineExpose({
    show,
})


</script>

<style lang="scss" scoped></style>